//
//  KLRBScanViewController.m
//  KISSLOCK
//
//  Created by 华杨科技 on 2017/4/6.
//  Copyright © 2017年 陈宾鹏. All rights reserved.
//

#import "KLRBScanViewController.h"
#import "LBXScanWrapper.h"
#import "LBXScanResult.h"

#import "KLHelp.h"
#import "SSKeychain.h"
#import "JRToast.h"
#import "KLHttpAPI.h"

// 扫描界面VC
@interface KLRBScanViewController ()
@property (nonatomic, copy)NSString *lockName; // 锁名
@property (nonatomic, copy)NSString *publicKey; //公钥
@property (nonatomic, copy)NSString *lockUname; // 锁别名
@end

@implementation KLRBScanViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        
        self.edgesForExtendedLayout = UIRectEdgeBottom;
    }
    // 设置导航栏
    [self naveSet];
    // 绘制底部按钮视图
    if (_isQQSimulator) {
        [self drawTitle];
        [self.view bringSubviewToFront:_topTitle];
    }else {
        _topTitle.hidden = YES;
    }
}

// 初始化导航栏
- (void)naveSet {
    self.title = @"扫描二维码";
    self.view.backgroundColor = [UIColor blackColor];
    
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:(UIControlEventTouchUpInside)];
    }];
} - (void)doBack:(UIButton *)sender {
    // 取消扫描， 返回
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

//绘制扫描区域
- (void)drawTitle
{
    if (!_topTitle)
    {
        self.topTitle = [[UILabel alloc]init];
        _topTitle.bounds = CGRectMake(0, 0, 145, 60);
        _topTitle.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 50);
        
        //3.5inch iphone
        if ([UIScreen mainScreen].bounds.size.height <= 568 )
        {
            _topTitle.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 38);
            _topTitle.font = [UIFont systemFontOfSize:14];
        }
        
        _topTitle.textAlignment = NSTextAlignmentCenter;
        _topTitle.numberOfLines = 0;
        _topTitle.text = @"将取景框对准二维码即可自动扫描";
        _topTitle.textColor = [UIColor whiteColor];
        [self.view addSubview:_topTitle];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.qRScanView addObserver:self forKeyPath:@"isStopInit" options:NSKeyValueObservingOptionNew context:nil];
    });
    
}

//开关闪光灯
- (void)openOrCloseFlash
{
    [super openOrCloseFlash];
    
    if (self.isOpenFlash)
    {
        [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_down"] forState:UIControlStateNormal];
    }
    else
        [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal];
}


// 相册
- (void)openPhoto{
    if ([LBXScanWrapper isGetPhotoPermission]) {
        // 打开相机
        [self openLocalPhoto];
        
    }else {
        NSLog(@"没有相册权限，请到设置->隐私中开启本程序相册权限");
    }
}

#pragma mark 处理扫描结果
- (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array
{

    // 没扫描到数据
    if (array.count < 1)
    {
        NSLog(@"解析出错");
        return;
    }
    
    for (LBXScanResult *result in array) {
        
        NSLog(@"scanResult:%@",result.strScanned);
    }
    
    // 只取第一个二维码结果
    LBXScanResult *scanResult = array[0];
    
    // 扫描到的字符串,对照通讯协议--》扫码数据格式
    NSString *strResult = scanResult.strScanned;
    
    // 长度不足,直接返回
    // 4 + 6 + 4 + 216
    if (strResult.length < 230) {
        // 提示信息
        // 没有扫描到钥匙结果
        [JRToast showWithText:@"二维码格式有误..."];
        
        //震动提醒
        [LBXScanWrapper systemVibrate];
        //声音提醒
        [LBXScanWrapper systemSound];
        
        // 直接返回
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        NSString *gongyue = [strResult substringFromIndex:14];
        if (gongyue.length == 216) {
            self.publicKey = gongyue; // 公钥
            NSString *modelStr = [strResult substringWithRange:NSMakeRange(0, 4)]; // 型号
            NSString *numberStr = [strResult substringWithRange:NSMakeRange(10, 4)]; // 序号
            self.lockName = [NSString stringWithFormat:@"KissLock%@%@",modelStr,numberStr];
            self.lockUname = [NSString stringWithFormat:@"KissLock%@%@",modelStr,numberStr];
            NSLog(@"公钥:%@ 锁名:%@",self.publicKey,self.lockUname);
            
            // 公钥保存到本地
            [self memoryPublicKeysWithKey:self.lockName value:self
             .publicKey];
            
            // 添加锁
            [KLHelp showTextHUDforView:self.view text:@"正在添加..."];
            [KLHttpAPI requestAddLockWithLockName:self.lockName lockUname:self.lockUname code:self.publicKey completionHandler:^(NSString *responseString) {
                
                NSLog(@"返回数据:%@",responseString);
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                
                NSDictionary *info = [KLHelp dictionaryWithJsonString:responseString];
                NSString *msg = [info objectForKey:@"msg"];
                [JRToast showWithText:msg];
                
                NSString *isSuccess = [info objectForKey:@"success"];
                if (isSuccess.integerValue == 1) {
                    // 锁信息保存到 NSUserDefaults
                    NSDictionary *lockInfo = [info objectForKey:@"infor"];
                    [[NSUserDefaults standardUserDefaults] setObject:lockInfo forKey:self.lockUname];
                    
                    // 扫描成功发送刷新列表通知
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"scanSuccess" object:nil userInfo:nil];
                }
                
                [self.navigationController popViewControllerAnimated:YES];
                
            } errorHandler:^(NSString *error) {
                
                [KLHelp hideAllHUDsForView:self.view animated:YES];
                [self.navigationController popViewControllerAnimated:YES];
                
            }];
        }
    }
}

//- (void)showNextVCWithScanResult:(LBXScanResult *)result {
//    KLRBScanResultViewController *resultVC = [[KLRBScanResultViewController alloc] init];
//    resultVC.resultStr = result.strScanned;
//    
//    [self.navigationController pushViewController:resultVC animated:YES];
//}


#pragma mark 公钥保存到本地
- (void)memoryPublicKeysWithKey:(NSString *)key value:(NSString *)value {
    
    NSString *jsonStr = [SSKeychain passwordForService:@"com.kisslock.guoyang" account:@"publickeysdic"];
    NSLog(@"publickeysdic:%@",jsonStr);
    NSDictionary *keysDic = [KLHelp dictionaryWithJsonString:jsonStr];
    NSMutableDictionary *publickeysdic;
    if(keysDic == nil){
        publickeysdic = [NSMutableDictionary dictionary];
    }else{
        publickeysdic = [NSMutableDictionary dictionaryWithDictionary:keysDic];
    }
    [publickeysdic setObject:value forKey:key];
    [SSKeychain setPassword:[KLHelp dictionaryToJson:publickeysdic] forService:@"com.kisslock.guoyang" account:@"publickeysdic"];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    // 开灯
    CGSize size = CGSizeMake(65, 87);
    self.btnFlash = [[UIButton alloc]init];
    _btnFlash.frame = CGRectMake(UI_View_Width/5, UI_View_Height-200, size.width, size.height);
    [_btnFlash setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_flash_nor"] forState:UIControlStateNormal];
    [_btnFlash addTarget:self action:@selector(openOrCloseFlash) forControlEvents:UIControlEventTouchUpInside];
    
    // 相册
    self.btnPhoto = [[UIButton alloc]init];
    self.btnPhoto.frame = CGRectMake(UI_View_Width/5*4-size.width, UI_View_Height-200, size.width, size.height);
    
    [_btnPhoto setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_photo_nor"] forState:UIControlStateNormal];
    [_btnPhoto setImage:[UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_btn_photo_down"] forState:UIControlStateHighlighted];
    [_btnPhoto addTarget:self action:@selector(openPhoto) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btnFlash];
    [self.view addSubview:self.btnPhoto];
}

-(void)dealloc{
    [self.qRScanView removeObserver:self forKeyPath:@"isStopInit"];
}
@end
